//
//  SY_Setting_MakeSurePhoneNumViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 16/8/17.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "SY_Setting_MakeSurePhoneNumViewController.h"
#import "SY_Setting_NewPassWordViewController.h"

@interface SY_Setting_MakeSurePhoneNumViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIAlertViewDelegate>
{
    UIButton *_nextBtn;
    
    UIButton *_verifyBtn;
    
    NSString  *_leftStr;
    UILabel  *titleLabel;
    
    NSString *verifycode;
    NSString * btnTitle;
    NSTimer *ti;//计时器
    int time;//倒计时
    
    UITextField *_phoneNumTextField;
    UITextField *_verificationCode;
    
    BOOL phoneNum;
}

@property (nonatomic, strong) UITableView *myTable;

@end

@implementation SY_Setting_MakeSurePhoneNumViewController


- (void)loadView {
    [super loadView];
    [self.view setBackgroundColor:RGBCOLOR(240,239,245)];
    
    if ([self.typeNum isEqualToString:@"1"]) {
        
        self.navBar.nav_titleLabel.text = @"修改密码";
        _leftStr = @"账号";
        
    }else if ([self.typeNum isEqualToString:@"2"]) {
        
        self.navBar.nav_titleLabel.text = @"更换手机号";
        _leftStr = @"当前手机号";
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.myTable];
    
    _nextBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [_nextBtn setFrame:CGRectMake(12, 156+SafeAreaTopHeight, SCREENWIDTH - 24, 38)];
    _nextBtn.layer.cornerRadius = 5;
    [_nextBtn setTitle:@"下一步" forState:(UIControlStateNormal)];
    [_nextBtn setTintColor:[UIColor whiteColor]];
    [_nextBtn setBackgroundColor:DEFAULTCOLOR];
    [_nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    _nextBtn.enabled = NO;
    _nextBtn.alpha = 0.5;
    [self.view addSubview:_nextBtn];
    
    phoneNum = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TabelViewDataSource & UITabelViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
    
    if (cell == nil) {
        cell  = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"identifier"];
        
        
        
    }
    
    for (UIView *view in cell.contentView.subviews) {
        
        if (view.tag > 50) {
            [view removeFromSuperview];
        }
    }
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 82, 44)];
    
    titleLabel.tag = 51;
    [titleLabel setFont:[UIFont systemFontOfSize:16]];
    
    [cell.contentView addSubview:titleLabel];
    
    
    
    if (indexPath.row == 0) {
        
        titleLabel.text = _leftStr;
        
        _phoneNumTextField = [[UITextField alloc]initWithFrame:CGRectMake(107, 0, 200, 44)];
        [_phoneNumTextField setFont:[UIFont systemFontOfSize:16]];
        _phoneNumTextField.tag = 54;
        [_phoneNumTextField setTextColor:RGBCOLOR(59, 59, 59)];
        _phoneNumTextField.keyboardType = UIKeyboardTypePhonePad;
        [_phoneNumTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        _phoneNumTextField.delegate = self;
        [cell.contentView addSubview:_phoneNumTextField];
        [self displayPhoneNumberMark:phoneNum];
        
        
    }else if (indexPath.row == 1) {
        
        titleLabel.text = @"验证码";
        
        _verifyBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _verifyBtn.tag = 52;
        [_verifyBtn setFrame:CGRectMake(SCREENWIDTH - 82, 7, 70, 30)];
        [_verifyBtn addTarget:self action:@selector(getVerificationCode) forControlEvents:(UIControlEventTouchUpInside)];
        [_verifyBtn setTitle:@"获取" forState:UIControlStateNormal];
        [_verifyBtn setTitleColor:DEFAULTCOLOR forState:(UIControlStateNormal)];
        [_verifyBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        _verifyBtn.layer.cornerRadius=3;
        _verifyBtn.layer.borderWidth = 0.5;
        _verifyBtn.layer.borderColor = [DEFAULTCOLOR CGColor];
        [cell.contentView addSubview:_verifyBtn];
        
        _verificationCode = [[UITextField alloc]initWithFrame:CGRectMake(107, 0, 200, 44)];
        [_verificationCode addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        _verificationCode.tag = 53;
        _verificationCode.delegate = self;
        _verificationCode.placeholder = @"请输入验证码";
        [_verificationCode setFont:[UIFont systemFontOfSize:16]];
        [_verificationCode setTextColor:RGBCOLOR(59, 59, 59)];
        _verificationCode.keyboardType = UIKeyboardTypeNumberPad;
        [cell.contentView addSubview:_verificationCode];
        
    }
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, 43.5, SCREENWIDTH, 0.5)];
    [lineView setBackgroundColor:colorFromHex(@"#DEDEDE")];
    [cell.contentView addSubview:lineView];
    
    if (indexPath.row == 1) {
        lineView.x = 0;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)getVerificationCode {
    
    if (_phoneNumTextField.text.length == 0) {
        
        [Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_VerifyCode_get" forKey:@"method"];
    
    if ([[_nextBtn titleForState:UIControlStateNormal] isEqualToString:@"下一步"]) {
        [dict setObject:self.typeNum forKey:@"Type"];//0注册 1 重置密码 2修改手机号（号码1） 3修改手机号（号码2）  4绑定手机号
        
    }else
    {
        [dict setObject:self.typeNum forKey:@"Type"];
    }
    [dict setObject:_phoneNumTextField.text forKey:@"Mobile"];
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        NSLog(@"%@", jsonObject);
        self->verifycode=[[jsonObject objectForKey:@"re_data"] objectForKey:@"verifycode"];
        
        //60s倒计时
        /*启动计时器*/
        self->ti= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
        self->time=60;
        
        self->_verifyBtn.enabled=NO;
        self->_verifyBtn.layer.borderWidth = 0;
        
        [self->_verifyBtn setTitleColor:colorFromHex(@"979797") forState:UIControlStateNormal];
        [self->_verifyBtn setTitle:[NSString stringWithFormat:@"等待%d秒",self->time] forState:UIControlStateNormal];
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
}

- (void)nextBtnAction:(UIButton *)sender {

    if ([self.typeNum isEqualToString:@"1"]){
        SY_Setting_NewPassWordViewController *newVC = [[SY_Setting_NewPassWordViewController alloc]init];
        newVC.verificationCodeStr = _verificationCode.text;
        [self.navigationController pushViewController:newVC animated:YES
         ];
    }else {
        btnTitle = [sender titleForState:UIControlStateNormal];
        if ([btnTitle isEqualToString:@"下一步"]) {
            
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
            [dict setObject:@"api_verifycode_verify" forKey:@"method"];
            [dict setObject:_verificationCode.text forKey:@"verify"];
            [dict setObject:_phoneNumTextField.text forKey:@"mobile"];
            [dict setObject:@"2" forKey:@"type"];
            [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
                NSLog(@"%@", jsonObject);
                
                if ([self.typeNum isEqualToString:@"2"]) {
                    self->_leftStr = @"新手机号";
                    self->_phoneNumTextField.enabled = YES;
                    self->_phoneNumTextField.text = nil;
                    self->_verificationCode.text = nil;
                    self.typeNum = @"3";
                    [self->_nextBtn setTitle:@"完成" forState:UIControlStateNormal];
                    self->_nextBtn.enabled = NO;
                    self->_nextBtn.alpha = 0.5;
                    self->phoneNum = NO;
                    
                    [self->ti invalidate];
                    self->_verifyBtn.enabled=YES;
                    [self->_verifyBtn setTitleColor:DEFAULTCOLOR forState:UIControlStateNormal];
                    [self->_verifyBtn setTitle:@"获取" forState:UIControlStateNormal];
                    self->_verifyBtn.layer.borderWidth = 0.5;
                    
                    [self->_myTable reloadData];
                    
                }else if ([self.typeNum isEqualToString:@"1"]){
                    SY_Setting_NewPassWordViewController *newVC = [[SY_Setting_NewPassWordViewController alloc]init];
                    [self.navigationController pushViewController:newVC animated:YES
                     ];
                }
                
                [self->_verificationCode resignFirstResponder];
                [self displayPhoneNumberMark:NO];
                
            } failure:^(NSInteger recode, NSError * error){
            }];
        }else if ([btnTitle isEqualToString:@"完成"]){
            //[self setNavigationLeftBtnWithTarget:self.navigationController andAction:@selector(popViewControllerAnimated:)];
            NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
            [dict setObject:@"api_verifycode_verify" forKey:@"method"];
            [dict setObject:_verificationCode.text forKey:@"verify"];
            [dict setObject:_phoneNumTextField.text forKey:@"mobile"];
            [dict setObject:@"3" forKey:@"type"];
            [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
                [self changePhoneNumber];
                
            } failure:^(NSInteger recode, NSError * error){
                
            }];
            
        }
    }
    
    
    
}

-(void)changePhoneNumber
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_usermobile_edit" forKey:@"method"];
    [dict setObject:USERID forKey:@"userid"];
    [dict setObject:_phoneNumTextField.text forKey:@"Mobile"];
    [Utils get:nil parameters:dict success:^(NSInteger recode ,id jsonObject){
        NSLog(@"%@", jsonObject);
        NSDictionary * dict = (NSDictionary *)jsonObject;
        NSDictionary * personalImformation = [dict objectForKey:@"re_data"];
        [SyUserInfomation personalImformationSaveWtih:personalImformation];
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:[jsonObject objectForKey:@"re_info"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    } failure:^(NSInteger recode, NSError * error){
    }];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

-(void)timerFireMethod:(NSTimer *)timer{
    
    time-=1;
    [self->_verifyBtn setTitle:[NSString stringWithFormat:@"等待%d秒",time] forState:UIControlStateNormal];
    
    // lab.text=[NSString stringWithFormat:@"等待%d秒",time];
    if (time==0) {
        self->_verifyBtn.enabled=YES;
        //[self->_verifyBtn setBackgroundColor:[SEATools stringToColor:@"fffbb5"]];
        [self->_verifyBtn setTitleColor:DEFAULTCOLOR forState:UIControlStateNormal];
        
        [self->_verifyBtn setTitle:@"获取" forState:UIControlStateNormal];
        self->_verifyBtn.layer.borderWidth = 0.5;
        if ([timer isValid] == YES) {
            [timer invalidate];
            timer = nil;
        }
    }
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == _verificationCode) {
        
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
        }
        
        if (textField.text.length == 6) {
            _nextBtn.enabled = YES;
            _nextBtn.alpha = 1;
        }else{
            _nextBtn.enabled = NO;
            _nextBtn.alpha = 0.5;
        }
        
        
    }else {
        
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
}

- (void)displayPhoneNumberMark:(BOOL)display
{
    if (display) {
        _phoneNumTextField.enabled = NO;
        _phoneNumTextField.text = [SYAccountTool ShareAccount].account.mobile;
    }else
    {
        _phoneNumTextField.enabled = YES;
        _phoneNumTextField.text = nil;
        _verificationCode.text=nil;
    }
}

#pragma mark - Get

- (UITableView *)myTable {
    if (_myTable == nil) {
        _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, 88) style:(UITableViewStylePlain)];
        _myTable.delegate = self;
        _myTable.dataSource = self;
        _myTable.rowHeight = 44;
        _myTable.scrollEnabled = NO;
        _myTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _myTable;
}

@end
